package com.kcht.itsed.mws.alefacade.stdfacade.impl;

import com.kcht.itsed.mws.alefacade.exceptions.DuplicateNameException;
import com.kcht.itsed.mws.alefacade.exceptions.InUseException;
import com.kcht.itsed.mws.alefacade.exceptions.NoSuchNameException;
import com.kcht.itsed.mws.alefacade.exceptions.TMSpecValidationException;
import com.kcht.itsed.mws.alefacade.stdfacade.ALETM;
import com.kcht.itsed.mws.aleframework.intf.ITagMemoryContainer;
import com.kcht.itsed.mws.alemodel.TMSpec;
import com.kcht.itsed.mws.extendmodel.jpa.TagMemoryEntity;
import com.kcht.itsed.mws.persist.dao.ITagMemoryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class ALETM_IMPL implements ALETM{
	
	@Autowired
	ITagMemoryDao tmDao;
	@Autowired ITagMemoryContainer tagMemoryContainer;

	@Override
	public void defineTMSpec(String specName, TMSpec spec) throws DuplicateNameException, TMSpecValidationException {
		Optional<TagMemoryEntity> existEntity = tmDao.findBySpecName(specName);
		if(existEntity.isPresent())throw new DuplicateNameException("TM spec name ["+specName+"] already existed.");

		//TODO 校验规则
		TagMemoryEntity tme = new TagMemoryEntity();
		tme.setTmName(specName);
		tme.setTmSpec(spec);
		tmDao.insert(tme);
		//TODO 添加该TM规则关联的Field规则

		tagMemoryContainer.updateTMSpec(specName, spec);
	}

	@Override
	public void undefineTMSpec(String specName) throws NoSuchNameException, InUseException {
		Optional<TagMemoryEntity> existEntity = tmDao.findBySpecName(specName);
		if(!existEntity.isPresent())throw new NoSuchNameException("TM Spec ["+specName+"] not existed.");
		//TODO 检查是否在使用
		tmDao.dropTagMemoryEntity(specName);
		tagMemoryContainer.removeTMSpec(specName);
	}

	@Override
	public TMSpec getTMSpec(String specName) throws NoSuchNameException {
		Optional<TagMemoryEntity> eo = tmDao.findBySpecName(specName);
		eo.orElseThrow(()->new NoSuchNameException("No TM spec ["+specName+"]"));
		return eo.get().getTmSpec();
	}

	@Override
	public List<String> getTMSpecNames() {
		return tmDao.queryTagMemory();
	}


}
